import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import routes from './routes'
import { store } from '../store/index'

const whiteList = ['/', '/login']

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to: any, from: any, next: any) => {
  window.document.title = to.meta.title
  // next()
  const isLogin = store.getters['common/isLogin']
  if (isLogin) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }

})

router.onError((err, to, from) => {
  console.log(to.fullPath, '--to\n', from.fullPath, '--form\n', JSON.parse(JSON.stringify(err)), '\n', '路由错误')
  const jsModulePattern = /dynamically imported module/g
  const jsLoadPattern = /Failed to load module script/g
  const isFailed = err.message.match(jsModulePattern || jsLoadPattern)
//   if (isFailed) window.location.reload()
})

export default router
